<template>
	<view>
	  <view class="location-info"> 当前位置：{{ locationName }} </view>
	  <map
		style="width: 100%; height: 300px"
		:latitude="latitude"
		:longitude="longitude"
		:markers="covers"
		@tap="handleMapTap"
		:polyline="polyline"
		show-compass
		show-location
	  >
	  </map>
  
	  <button @click="handleWalk" >步行开始</button>
	  <button @click="handleCart" >开始</button>
	</view>
  </template>
  
  <script>
  import QQMapWX from '../../common/qqmap-wx-jssdk.js'
  export default {
	data() {
	  return {
		key: "5B3BZ-GSD6J-MJHFF-DNTPI-HKQ47-7NBD4", // key
		// key: "SQYBZ-GEGRF-7YJJL-JCRZJ-BYD32-2XBZV", // key 被人的 key
		map: {},
  
		id: 0, // 使用 marker点击事件 需要填写id
		latitude: 29.279353,
		longitude: 120.044455,
		locationName: "未选择位置",
		covers: [
		  {
			id: 1,
			latitude: 29.279353,
			longitude: 120.044455,
			iconPath: "../../static/car.png",
			width: 30,
			height: 30,
			callout: {
			  content: `起点位置: 哈哈
			  你在说： 123
			  `,
			  color: '#fff',
			  fontSize: 14,
			  borderRadius: 3,
			  bgColor: '#43553f',
			  padding: 5,
			  display: 'ALWAYS',  // 常显
			  textAlign: 'center',
			}
		  },
		  {
			id: 2,
			latitude: 29.280259,
			longitude: 120.048154,
			iconPath: "../../static/car2.png",
			width: 30,
			height: 30,
			callout: {
			  content: '终点位置',
			  color: '#000000',
			  fontSize: 14,
			  borderRadius: 3,
			  bgColor: '#ffffff',
			  padding: 5,
			  display: 'ALWAYS',
			  textAlign: 'center'
			}
		  },
		],
		polyline: [
		  {
			points: [
			  { latitude: 29.279353, longitude: 120.044455 },
			  { latitude: 29.278453, longitude: 120.043455 },
			  { latitude: 29.280259, longitude: 120.048154 },
			],
			color: '#b8ff13dd',
			width: 4,
		  },
		],
		startPoint: {
		  latitude: 29.279353,
		  longitude: 120.044455,
		},
		endPoint: {
		  latitude: 29.280259,
		  longitude: 120.048154,
		},
  
		currentIndex: 0, // 当前移动到的点
		interval: null // 动画的定时器
	  };
	},
	onLoad() {
	  this.qqmapsdk = new QQMapWX({
		  key: this.key  // 自己申请的key值
	  })
	},
	methods: {
	  handleCart() {
		console.log('== 开始移动小汽车')
		// 清除可能存在的之前的定时器
		if (this.interval) {
		  clearInterval(this.interval);
		}
		
		// 重置起始位置
		this.currentIndex = 0;
		
		// 获取路线点数组
		const points = this.polyline[0].points;
		
		// 更新小车位置的函数
		const updateCarPosition = () => {
		  if (this.currentIndex >= points.length) {
			// 到达终点，清除定时器
			clearInterval(this.interval);
			return;
		  }
		  
		  // 获取当前点的坐标
		  const currentPoint = points[this.currentIndex];
		  
		  // 计算小车朝向角度（如果有下一个点的话）
		  let rotation = 0;
		  if (this.currentIndex < points.length - 1) {
			const nextPoint = points[this.currentIndex + 1];
			// 计算角度
			const dx = nextPoint.longitude - currentPoint.longitude;
			const dy = nextPoint.latitude - currentPoint.latitude;
			rotation = Math.atan2(dy, dx) * 180 / Math.PI;
		  }
		  
		  // 更新小车标记位置
		  this.covers = [
			{
			  ...this.covers[0], // 保持起点标记不变
			},
			{
			  ...this.covers[1], // 保持终点标记不变
			},
			{
			  id: 3,
			  latitude: currentPoint.latitude,
			  longitude: currentPoint.longitude,
			  iconPath: "../../static/car.png",
			  width: 30,
			  height: 30,
			  rotate: rotation, // 设置小车旋转角度
			  anchor: {
				x: 0.5,
				y: 0.5
			  },
			  callout: {
				content: '正在移动中...',
				color: '#ffffff',
				fontSize: 12,
				borderRadius: 4,
				bgColor: '#000000',
				padding: 5,
				display: 'ALWAYS',
				textAlign: 'center'
			  }
			}
		  ];
		  
		  this.currentIndex++;
		};
		
		// 立即更新一次位置
		updateCarPosition();
		
		// 设置定时器，每隔一定时间移动一次
		this.interval = setInterval(updateCarPosition, 1000); // 每秒移动一次，可以调整时间间隔
	  },
  
	  handleWalk() {
		console.log('== 开始步行路线规划')
		const that = this;
  
		this.qqmapsdk.direction({
		  mode: 'walking',  // 步行
		  from: {   // 起点
			latitude: this.startPoint.latitude,
			longitude: this.startPoint.longitude
		  },
		  to: {     // 终点
			latitude: this.endPoint.latitude,
			longitude: this.endPoint.longitude
		  },
		  success: function(res) {
			console.log('== 路线规划结果 ', res);
			var ret = res.result;
			if (ret.routes && ret.routes.length > 0) {
			  var coors = ret.routes[0].polyline;
			  var pl = [];  // 点串数组
			  
			  //坐标解压（补充：解压后的坐标点会存在三到四位小数）
			  var kr = 1000000;
			  for (var i = 2; i < coors.length; i++) {
				coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr;
			  }
			  
			  //将解压后的坐标放入点串数组pl中
			  for (var i = 0; i < coors.length; i += 2) {
				pl.push({ 
				  latitude: coors[i], 
				  longitude: coors[i + 1] 
				})
			  }
			  
			  //设置polyline属性，将路线显示出来
			  that.polyline = [{
				points: pl,
				color: '#b8ff13dd',
				width: 4
			  }];
			} else {
			  console.error('路线规划失败：没有找到路线');
			}
		  },
		  fail: function(error) {
			console.error('路线规划失败：', error);
			uni.showToast({
			  title: '路线规划失败',
			  icon: 'none'
			});
		  }
		});
	  },
  
	  // 当点击地图时更新起点或终点
	  handleMapTap(e) {
		if (!e) return;
		
		console.log("== e ", e);
		const { latitude, longitude } = e.detail;
  
		this.endPoint = { latitude, longitude };
		
		// 更新标记，添加 callout 配置
		this.covers = [
		  {
			id: 1,
			latitude: this.startPoint.latitude,
			longitude: this.startPoint.longitude,
			iconPath: "../../static/car.png",
			width: 30,
			height: 30,
			callout: {
			  content: '起点',
			  color: '#000000',
			  fontSize: 14,
			  borderRadius: 3,
			  bgColor: '#ffffff',
			  padding: 5,
			  display: 'ALWAYS',  // 常显
			  textAlign: 'center'
			}
		  },
		  {
			id: 2,
			latitude: this.endPoint.latitude,
			longitude: this.endPoint.longitude,
			iconPath: "../../static/car2.png",
			width: 30,
			height: 30,
			callout: {
			  content: '终点\n' + this.locationName,  // 可以显示地址信息
			  color: '#000000',
			  fontSize: 14,
			  borderRadius: 3,
			  bgColor: '#ffffff',
			  padding: 5,
			  display: 'ALWAYS',
			  textAlign: 'center'
			}
		  }
		];
  
		// 调用腾讯地图逆地址解析服务
		uni.request({
		  url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&get_poi=1&key=${this.key}`,
		  method: "GET",
		  success: (res) => {
			console.log("== res ", res);
			if (res.data.status === 0) {
			  const address =
				res.data.result.formatted_addresses?.recommend ||
				res.data.result.address;
			  this.locationName = address;
			} else {
			  this.locationName = `获取位置信息失败(${res.data.message})`;
			}
		  },
		  fail: (err) => {
			console.error("请求失败：", err);
			this.locationName = "获取位置信息失败";
		  },
		});
	  },
  
	  // 在组件销毁时清除定时器
	  beforeDestroy() {
		if (this.interval) {
		  clearInterval(this.interval);
		}
	  }
	},
  };
  </script>
  
  <style>
  .container {
	padding: 0px;
	margin: 0px;
	width: 100%;
  }
  
  .location-info {
	padding: 10px;
	background-color: #fff;
	text-align: center;
	font-size: 14px;
  }
  </style>
  